<template>
  <div class="main-table-data flex-v">
    <div class="space" style="border-bottom: none;">
      <div class="title-bar no-select">
        <div class="auto-flex">
          <strong>数据</strong>
        </div>
        <div>
          <button type="button" class="btn btn-sm btn-success"
            v-if="$root.is.local"
            @click="$root.openFile($options.__file)"
          >打开组件</button>
        </div>
        <div v-if="curTable">
          <button type="button"
            @click="ld.isShowRowIndex ? delete ld.isShowRowIndex : (ld.isShowRowIndex = true)"
            :class="['btn btn-sm btn-default', {active: ld.isShowRowIndex}]"
          >
            <i class="glyphicon glyphicon-list"></i>
            <span>{{ ld.isShowRowIndex ? '隐藏序号' : '显示序号'}}</span>
          </button>
          <button type="button"
            :class="['btn btn-sm btn-' + (ld.isShowStructure ? 'primary' : 'default')]"
            @click="ld.isShowStructure = !ld.isShowStructure; ld.isShowStructure && ($refs.scrollEl.scrollTop = 0)"
          >
            <i class="glyphicon glyphicon-tent"></i>
            <span>库表结构</span>
          </button>
          
          <button type="button" class="btn btn-sm btn-info"
            @click="$root.copy(data.list)"
          >
            <i class="glyphicon glyphicon-copy"></i>
            <span>复制</span>
          </button>
          <button type="button"  @click="cmd('添加一行')" class="btn btn-sm btn-success">
            <i class="glyphicon glyphicon-plus"></i>
            <span>添加一行</span>
          </button>
          
          <a-popconfirm
            :title="`确定要 TRUNCATE TABLE ${dbTable} 吗？`"
            @confirm="cmd('清空')"
          >
            <button type="button" class="btn btn-sm btn-danger">
              <i class="glyphicon glyphicon-trash"></i>
              <span>清空</span>
            </button>
          </a-popconfirm>
        </div>
      </div>
    </div>

    <div class="auto-flex" ref="scrollEl" style="scroll-behavior: smooth;">
      <div class="ib space" style="padding-top: 0;">
        <div class="flex-h" v-if="ld.isShowStructure && fields.length > 0" style="margin-bottom: 1.5em;">
          <div>
            <div v-if="scDB">
              <pre
                :class="{'text-danger bold': scDB?.endsWith('获取失败')}"
                @contextmenu="$root.copy(scDB)"
              >{{ scDB }}</pre>
            </div>
            <div v-if="scTable">
              <pre
                @contextmenu="$root.copy(scTable)"
              >{{ scTable }}</pre>
            </div>
          </div>
          <div v-if="fields.length > 0">
            <table class="table-data table-fix-head">
              <thead>
                <tr>
                  <th v-for="(v, idx) in fieldKeys" :key="idx">{{ v }}</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, idx) in field.list" :key="idx">
                  <td
                    v-for="(key, idxKey) in fieldKeys"
                    :key="idxKey"
                    @contextmenu="$root.copy(formatField(row[key]))"
                    v-html="formatField_(row[key])"
                  ></td>
                  <td>
                    <button @click="cmd('编辑字段', row)" type="button" class="btn btn-xs btn-warning">
                      <i class="glyphicon glyphicon-pencil"></i>
                    </button>

                    <button @click="cmd('删除字段', row)" type="button" class="btn btn-xs btn-danger">
                      <i class="glyphicon glyphicon-trash"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- <div class="no-data" v-if="!table.list.length && !table.isLoading" style="padding-top: .35em;">暂无数据</div> -->

        <div class="c" v-if="!field.list.length && field.isLoading" style="padding-top: 4px;">
          <SmartLoading v-if="field.isLoading"></SmartLoading>
          <div v-else class="no-data">暂无数据</div>
        </div>

        <div class="relative" v-if="fields.length > 0">
          <table class="table-data table-fix-head table-fix-r">
            <thead>
              <tr>
                <th v-if="ld.isShowRowIndex">序号</th>
                <th
                  v-for="(v, idx) in field.list"
                  :key="idx"
                  @click="$root.copy(v.Field)"
                >{{ v.Field }}</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="!data.list.length">
                <td :colspan="fields.length + 1 + (ld.isShowRowIndex ? 1 : 0)">
                  <div v-if="!data.list.length" class="space2">
                    <SmartLoading v-if="data.isLoading"></SmartLoading>
                    <div v-else class="no-data">暂无数据</div>
                  </div>
                </td>
              </tr>
              <tr
                v-for="(row, idxRow) in data.list"
                :key="idxRow + page.cur * page.size"
                :data-id="idxRow + page.cur * page.size"
              >
                <td v-if="ld.isShowRowIndex">{{ idxRow + (page.cur - 1) * page.size + 1 }}</td>
                <td
                  v-for="(f, idx) in field.list"
                  :key="idx"
                >
                  <a-tooltip
                    :destroy-tooltip-on-hide="true"
                    v-if="f.Type === 'json' || row[f.Field]?.length > 100"
                  >
                    <template #title>
                      <div class="scroll-wrapper"
                        @contextmenu="copyCell(f, row)"
                      >
                        <pre v-if="f.Type === 'json' ">{{ $root.formatJSON(row[f.Field]) }}</pre>
                        <pre v-else-if="row[f.Field].indexOf('\n') > -1 || (row[f.Field].startsWith('<') && row[f.Field].endsWith('>'))">{{ $root.formatXML(row[f.Field]) }}</pre>
                        <span v-else style="display: inline-block;">{{ row[f.Field] }}</span>
                      </div>
                    </template>
                    <span @contextmenu="copyCell(f, row)">{{ substr(row[f.Field]) }}</span>
                  </a-tooltip>
                  <span @contextmenu="copyCell(f, row)" v-else>{{ row[f.Field] }}</span>
                </td>
                <td>
                  <a-tooltip title="显示行">
                    <button @click="cmd('显示行', row)" type="button" class="btn btn-xs btn-primary">
                      <i class="glyphicon glyphicon-eye-open"></i>
                    </button>
                  </a-tooltip>
                  <a-tooltip title="复制行">
                    <button @click="$root.copy(row)" type="button" class="btn btn-xs btn-info">
                      <i class="glyphicon glyphicon-copy"></i>
                    </button>
                  </a-tooltip>
                  <button @click="cmd('编辑行', row)" type="button" class="btn btn-xs btn-warning">
                    <i class="glyphicon glyphicon-pencil"></i>
                  </button>
                  <a-popconfirm
                    :title="`确定要 delete from table where id=1 limit 1 吗？`"
                    @confirm="$parent.runSql('delete from table where id=1 limit 1')"
                  >
                    <button type="button" class="btn btn-xs btn-danger">
                      <i class="glyphicon glyphicon-trash"></i>
                    </button>
                  </a-popconfirm>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div class="wrap-pagin">
      <a-pagination
        v-model:current="page.cur"
        v-model:page-size="page.size"
        show-quick-jumper
        :total="page.total"
        @change="handlePageChange"
        :show-total="(total, range) => `${range[0]}-${range[1]} / 共 ${total} 条数据`"
        :showSizeChanger="true"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'main-table-data',
  data() {
    return {}
  },
  computed: {
    r() {
      return this.$root.router
    },
    ld() {
      return this.$root.ld
    },
    curTable() {
      return this.$parent.curTable
    },
    dbTable() {
      return this.$parent.dbTable
    },
    scDB() {
      return this.$parent.scDB
    },
    scTable() {
      return this.$parent.scTable
    },
    fieldKeys() {
      return this.$parent.fieldKeys
    },
    data() {
      return this.$parent.data
    },
    page() {
      return this.$parent.page
    },
    field() {
      return this.$parent.field
    },
    fields() {
      return this.$parent.fields
    },
    table() {
      return this.$parent.table
    },
  },
  watch: {},
  methods: {
    copyCell(f, row) {
      const str = row[f.Field]
      return this.$root.copy(f.Type === 'json' ? this.$root.formatJSON(str) : str)
    },
    formatField(str) {
      if (!str) return str + '';

      if (str.indexOf(`'`) > -1) {
        return str.replace(/\((.*?)\)/, (...arg) => {
          return `(\n${arg[1].split(',').map((v) => '  ' + v).join(',\n')}\n)`
        })
      } else {
        return str
      }
    },
    formatField_(str) {
      if (!str) return str;

      if (str.indexOf(`'`) > -1) {
        return str.replace(/\((.*?)\)/, (...arg) => {
          return `(\n${arg[1].split(',').map((v) => '&nbsp;&nbsp;' + v).join(',\n')}\n)`.replace(/\n/g, '<br>')
        })
      } else {
        return str
      }
    },
    async cmd(a, arg) {
      const vm = this.$root

      switch (a) {
        case '添加一行':
          console.log('添加一行')
          break
        case '清空':
          await this.$parent.runSql('TRUNCATE TABLE ' + this.dbTable)
          break
        case '编辑字段':
          console.log('编辑字段')
          break
        case '删除字段':
          await this.$parent.runSql(`ALTER TABLE ${this.dbTable} DROP COLUMN ${arg.Field}`)
          break
        case '显示行':
          vm.alert(`<pre style="text-align: left; margin: 0;" oncontextmenu="vm.copy(this.innerHTML)">${JSON.stringify(arg, 0, 2)}</pre>`)
          break
        case '编辑行':
          console.log('编辑行')
          break
        case '删除行':
          console.log('删除行')
          break
      }
    },
    handlePageChange(cur, size) {
      this.page.cur = cur
      this.page.size = size
    },
    substr(str) {
      return str?.length > 100 ? str.substring(0, 100) + '...' : str
    },
  },
  async mounted() {}
}
</script>

<style lang="less" scoped>
.main-table-data {
  height: 100%;
  display: flex; flex-direction: column;
  .table-data {
    white-space: nowrap;
  }
}

.wrap-pagin {
  padding: .75em 1em;
  background: var(--bgColor);
}
</style>